import Taro from '@tarojs/taro'
import { action, observable, computed } from 'mobx'

// apis
import * as shopAddressesApi from '../../../apis/shopAddressesApi'

// models
import ShopAddresses from '../../../models/ShopAddresses'

// store
import detailStore from '../detail/store'

class AddressListStore {
  @observable
  addressList: ShopAddresses[] = []

  @observable
  selectMode: boolean = false

  @observable
  selectedId: number | null = null

  @computed
  get selectedAddress() {
    return this.addressList.find(({ id }) => id === this.selectedId) || null
  }

  @action
  async init({ selectMode }: { selectMode: boolean } = { selectMode: false }) {
    Taro.showLoading({ title: '加载中...' })

    this.selectMode = selectMode

    const resp = await shopAddressesApi.getAddrByUserId({ userId: 1 })
    this.addressList = resp.data

    const defaultAddress = this.addressList.find(({ isDefault }) => isDefault === 1)
    if (!this.selectedId && defaultAddress) {
      this.selectedId = defaultAddress.id
    }

    Taro.hideLoading()
  }

  @action
  navigateToAdd = () => {
    Taro.chooseAddress()
    // this.navigateToDetail()
  }
  @action
  navigateToDetail = (address?: ShopAddresses) => {
    Taro.navigateTo({
      url: '/pages/address/detail/index',
    })
    if (address) {
      Taro.setNavigationBarTitle({ title: '编辑地址' })
    } else {
      Taro.setNavigationBarTitle({ title: '新增地址' })
    }
    detailStore.init({ address })
  }

  @action
  select = (id: number) => {
    this.selectedId = id
    Taro.navigateBack()
  }
}

export default new AddressListStore()
